package com.chant.startFarming.config;

import com.chant.startFarming.utils.AuthInterceptor;
import com.chant.startFarming.utils.LoginInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 第一个拦截器：负责获取token、查询Redis用户、保存到ThreadLocal、刷新token有效期
        registry.addInterceptor(new AuthInterceptor(stringRedisTemplate,objectMapper))
                .addPathPatterns("/**") // 拦截所有请求
                .excludePathPatterns(
                        "/swagger-ui.html",
                        "/webjars/**",       // 添加Swagger的静态资源路径
                        "/swagger-resources/**",
                        "/v2/api-docs",
                        "/csrf"
                )
                .order(0);

        // 第二个拦截器：负责查询ThreadLocal中的用户，如果不存在则拦截
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns(
                        "/users/login",     // 排除登录接口
                        "/swagger-ui.html",
                        "/webjars/**",       // 添加Swagger的静态资源路径
                        "/swagger-resources/**",
                        "/v2/api-docs",
                        "/csrf"
                )
                .order(1);

        // 第三个拦截器：负责查看用户的角色权限
//        registry.addInterceptor(new PermissionCheckInterceptor())
//                .addPathPatterns("/**")
//                .excludePathPatterns("/users/login").order(2); // 排除登录接口
    }
}